from django.http import JsonResponse
from django.views import View
from rest_framework.generics import ListCreateAPIView
from rest_framework.views import APIView

from users.models import User
from django_redis import get_redis_connection
from users.serializer import UserSerializer

import logging
logger = logging.getLogger('django')
import random
import re
import json

class SMSCodeView(View):
    """短信验证码"""

    def get(self, request, mobile):
        """
        :param request: 请求对象
        :param mobile: 手机号
        :return: JSON
        """

        redis_conn = get_redis_connection('verify_code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return JsonResponse({'code': 400,
                                 'errmsg': '发送短信过于频繁'})

        redis_conn = get_redis_connection('verify_code')

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)

        p1 = redis_conn.pipeline()

        p1.setex('sms_%s' % mobile, 300, sms_code)

        p1.setex('send_flag_%s' % mobile, 60, 1)

        p1.execute()

        return JsonResponse({'success': True,
                             'sms_code': sms_code,
                             'message': '发送短信成功'})


# 注册
class UserListView(ListCreateAPIView):

    serializer_class = UserSerializer

    queryset = User.objects.all()


class UserRegister(View):
    def post(self, request):
        """注册用户信息保存"""
        # ① 获取参数并进行校验
        req_data = json.loads(request.body.decode())
        username = req_data.get('username')
        password = req_data.get('password')
        mobile = req_data.get('mobile')
        sms_code = req_data.get('sms_code')

        if not all([username, password, mobile, sms_code]):
            return JsonResponse({'code': 400,
                                 'message': '缺少必传参数'})

        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400,
                                 'message': 'username格式错误'})

        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400,
                                 'message': 'password格式错误'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                 'message': '手机号格式错误'})

        # 短信验证码检验
        redis_conn = get_redis_connection('verify_code')
        sms_code_redis = redis_conn.get('sms_%s' % mobile)

        if not sms_code_redis:
            return JsonResponse({'code': 400,
                                 'message': '短信验证码过期'})

        if sms_code != sms_code_redis:
            return JsonResponse({'code': 400,
                                 'message': '短信验证码错误'})

        # ② 保存新增用户数据到数据库
        try:
            user = User.objects.create_user(username=username,
                                            password=password,
                                            mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400,
                                 'message': '数据库保存错误'})

        # JWT TOKEN
        from rest_framework_jwt.settings import api_settings

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # ③ 返回响应
        ret = {
            "id": user.id,
            "username": user.username,
            "mobile": user.mobile,
            "token": token,
            "avatar": user.avatar.name
        }
        return JsonResponse(ret)


# 个人信息
class UserMessage(APIView):
    # 获取个人详情
    def get(self, request):
        """
        ①获取登录用户的信息；
        ②返回信息数据。
        """
        print(request.headers)
        # permission_classes = [IsAdminUser]

        user = request.user
        print(user.id, user)
        current_user = User.objects.get(id=user.id)

        # current_user.labels获取到的是关系类型；
        # current_user.labels.all()获取到查询集；
        # JsonResponse没办法将查询集转为json，所以要用list()方法将查询集转换

        user_message = {
            "id": current_user.id,
            "username": current_user.username,
            "mobile": current_user.mobile,
            "realname": current_user.realname,
            "birthday": current_user.birthday,
            "sex": current_user.sex,
            "avatar": current_user.avatar,
            "website": current_user.website,
            "email": current_user.email,
            "city": current_user.city,
            "address": current_user.address,
            "labels": list(current_user.labels.all()),
            "questions": list(current_user.questions.all()),
            "answer_question": list(current_user.replies.all()),
            "collected_articles": list(current_user.collected_articles.all()),
            "enterpises": list(current_user.enterpises.all())
        }
        print(user_message)

        return JsonResponse(user_message)

    # 修改个人信息
    def put(self, request):
        """
        ① 获取传入数据；
        ② 传入user；
        ③ 返回数据。
        """
        # ①
        user_data = json.loads(request.body.decode())

        # 这里传过来的图片是二进制文件，要单独处理一下
        from fdfs_client.client import Fdfs_client
        import os
        from django.conf import settings

        client = Fdfs_client(r'C:\Users\HQ\Desktop\1\the-tenth-power\TenSquare\TenSquare\utils\fastdfs\client.conf')
        ret = client.upload_by_buffer(user_data['avatar'].encode())
        print(ret)

        nginx_url = 'http://192.168.19.131:8888/'
        avatar_url = nginx_url + ret['Remote file_id']
        print(avatar_url)

        # img_url = nginx_url + avatar_url

        # ②
        user = request.user
        print(user.id, user)
        current_user = User.objects.get(id=user.id)

        current_user.realname = user_data['realname']
        current_user.birthday = user_data['birthday']
        current_user.website = user_data['website']
        current_user.mobile = user_data['mobile']
        current_user.email = user_data['email']
        current_user.city = user_data['city']
        current_user.address = user_data['address']
        current_user.avatar = avatar_url

        current_user.save()

        # ③
        user_message = {
            "id": current_user.id,
            "username": current_user.username,
            "mobile": current_user.mobile,
            "realname": current_user.realname,
            "birthday": current_user.birthday,
            "sex": current_user.sex,
            "avatar": current_user.avatar,
            "website": current_user.website,
            "email": current_user.email,
            "city": current_user.city,
            "address": current_user.address,
            "labels": list(current_user.labels.all()),
            "questions": list(current_user.questions.all()),
            "answer_question": list(current_user.replies.all()),
            "collected_articles": list(current_user.collected_articles.all()),
            "enterpises": list(current_user.enterpises.all())
        }
        print(user_message)

        return JsonResponse(user_message)


# 修改密码
# class ChangePassword(APIView):
#     def put(self, request):
#         req_data = json.loads(request.body.decode())
#         print(req_data.password)

# 关注
class FollowUsers(View):
    def post(self, request, id):
        """
        ①根据urlurl获取到关注的用户id；
        ②将id存入user表的fans；
        ③返回要求数据。
        """
        # ①
        print(id)

        # ②
        user = request.user
        current_user = User.objects.get(id=user.id)
        print(type(current_user), current_user)
        current_user.fans.add(id)

        print("执行数据库操作")
        print("数据库存入成功" + current_user.fans)

        # ③
        return JsonResponse({
            "message": "关注成功！",
            "success": bool
        })
